package com.aiyige.page.my.merchandisemanagement.mmlearnvideo;


import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.aiyige.R;
import com.aiyige.arouter.Router;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseFragment;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.db.dao.LearnVideoModelDao;
import com.aiyige.base.db.table.LearnVideoModel;
import com.aiyige.base.eventbus.EventMMLearnVideoFilter;
import com.aiyige.base.eventbus.EventMMPublishProgressStatusUpdate;
import com.aiyige.base.eventbus.EventPublishProgressStatusUpdate;
import com.aiyige.base.eventbus.EventServerChangeMomentStatus;
import com.aiyige.model.Page;
import com.aiyige.model.moment.backup.TagBackup;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.page.detail.DetailPage;
import com.aiyige.page.my.merchandisemanagement.MMFilterable;
import com.aiyige.page.my.merchandisemanagement.mmlearnvideo.adapter.MMLearnVideoAdapter;
import com.aiyige.page.publish.selectinterest.model.PublishIndustryItem;
import com.aiyige.page.publish.selectinterest.model.PublishInterestItem;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.widget.CommonDataView;
import com.aiyige.utils.widget.LocalServerCommonDataView;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.DeleteBuilder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.ResponseBody;
import retrofit2.Call;

public class MMLearnVideoPage extends BaseFragment implements MMFilterable, CommonDataView.RetrofitStub, LocalServerCommonDataView.OperationStub {

    @BindView(R.id.cdv)
    LocalServerCommonDataView cdv;
    Unbinder unbinder;
    MMLearnVideoAdapter mmLearnVideoAdapter;

    Dao<LearnVideoModel, String> learnVideoModelDao;
    Integer filter = null;
    public static final int MOMENT_FILTER_ALL = 0;
    public static final int MOMENT_FILTER_PUBLISHED = 1;
    public static final int MOMENT_FILTER_NOT_PUBLISHED = 2;
    public static final int MOMENT_FILTER_IN_REVIEW = 3;
    public static final int MOMENT_FILTER_REJECTED = 4;


    public MMLearnVideoPage() {
    }


    public static MMLearnVideoPage newInstance() {
        MMLearnVideoPage fragment = new MMLearnVideoPage();
        fragment.setAutoRegisterEventBus(true);
        return fragment;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventMMLearnVideoFilter event) {
        cdv.refresh();
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(EventMMPublishProgressStatusUpdate event) {
        mmLearnVideoAdapter.getEventBus().post(new EventPublishProgressStatusUpdate());
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.page_mmlearn_video, container, false);
        unbinder = ButterKnife.bind(this, view);
        learnVideoModelDao = LearnVideoModelDao.getDao();
        mmLearnVideoAdapter = new MMLearnVideoAdapter(getActivity());
        cdv.config(mmLearnVideoAdapter, this, this);


        mmLearnVideoAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                LearnVideoModel learnVideoModel = mmLearnVideoAdapter.getItem(position);
                switch (learnVideoModel.getProgressStatus()) {
                    case PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE:
                    case PublishUtil.PROGRESS_STATUS_TRANSCODE_FINISH:
                    case PublishUtil.PROGRESS_STATUS_TRANSCODE_FAILED:
                    case PublishUtil.PROGRESS_STATUS_WAITING_UPLOAD:
                    case PublishUtil.PROGRESS_STATUS_UPLOADING:
                    case PublishUtil.PROGRESS_STATUS_UPLOAD_FINISH:
                    case PublishUtil.PROGRESS_STATUS_SUBMITTING:
                    case PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED:
                        ARouter.getInstance().build(ARouterConfig.UploadFilePage)
                                .withString("parentId", learnVideoModel.getId())
                                .withInt("parentType", PublishUtil.PARENT_TYPE_LEARN_VIDEO)
                                .navigation();
                        break;
                    case PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING:
                        ToastX.show(R.string.server_transcoding);
                        break;
                    default:
                        Router.start(learnVideoModel.getRouter());
                        break;
                }

            }
        });
        return view;
    }

    @Override
    public void onDestroyView() {
        cdv.getRecyclerView().setAdapter(null);
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    protected void initData() {
        cdv.doRefreshRequest();
    }

    @Override
    public Call<ResponseBody> call(long currentPage) {
        Integer momentFilter = MOMENT_FILTER_ALL;
        if (filter != null) {
            switch (filter) {
                case PublishUtil.PROGRESS_STATUS_PUBLISHED:
                    momentFilter = MOMENT_FILTER_PUBLISHED;
                    break;
                case PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED:
                    momentFilter = MOMENT_FILTER_NOT_PUBLISHED;
                    break;
                case PublishUtil.PROGRESS_STATUS_IN_REVIEW:
                    momentFilter = MOMENT_FILTER_IN_REVIEW;
                    break;
                case PublishUtil.PROGRESS_STATUS_REJECT:
                    momentFilter = MOMENT_FILTER_REJECTED;
                    break;
            }
        }
        return ApiManager.getService().merchandiseManagementMoment(20, currentPage, Arrays.asList(Moment.SUBJECT_VIDEO_COURSE), momentFilter);
    }

    @Override
    public CommonDataView.HandleResult handleResponse(String respJson, List resultList) {
        try {
            Page page = JSON.parseObject(respJson, Page.class);
            List<Moment> momentList = new LinkedList<>();
            if (!TextUtils.isEmpty(page.getContent())) {
                momentList.addAll(JSON.parseArray(page.getContent(), Moment.class));
            }
            for (Moment moment : momentList) {
                Moment record = new Moment(moment);
                int progressStatus;
                switch (record.getStatus()) {
                    case Moment.STATUS_IN_REVIEW:
                        progressStatus = PublishUtil.PROGRESS_STATUS_IN_REVIEW;
                        break;
                    case Moment.STATUS_REJECT:
                        progressStatus = PublishUtil.PROGRESS_STATUS_REJECT;
                        break;
                    case Moment.STATUS_PUT_ON:
                        progressStatus = PublishUtil.PROGRESS_STATUS_PUBLISHED;
                        break;
                    case Moment.STATUS_SAVE:
                        progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                        break;
                    case Moment.STATUS_REVIEW_PASSED:
                        progressStatus = PublishUtil.PROGRESS_STATUS_PUBLISHED;
                        break;
                    case Moment.STATUS_GET_OFF:
                        progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                        break;
                    case Moment.STATUS_TRANSCODING:
                        progressStatus = PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING;
                        break;
                    default:
                        progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                        break;
                }
                String categoryName = "";
                String subGroupType = "";
                String subGroupName = "";
                for (TagBackup tagBackup : record.getTags()) {
                    if (tagBackup == null) continue;
                    if (tagBackup.getId().equals(record.getCategoryId())) {
                        categoryName = tagBackup.getName() == null ? "" : tagBackup.getName();
                        subGroupType = tagBackup.getSubGroupType() == null ? "" : tagBackup.getSubGroupType();
                        subGroupName = tagBackup.getSubGroupName() == null ? "" : tagBackup.getSubGroupName();
                        break;
                    }
                }
                resultList.add(LearnVideoModel.newBuilder()
                        .title(record.getTitle())
                        .rejectReason(record.getRemark())
                        .coverUrl(ListUtil.isEmpty(record.getCover()) ? "" : record.getCover().get(0))
                        .introduction(record.getSummary())
                        .price(record.getCommodityBackup().getPrice())
//                        .interestCategory(JSON.toJSONString(PublishInterestItem.newBuilder()
//                                .id(record.getCategoryId())
//                                .title(categoryName)
//                                .parent(PublishIndustryItem.newBuilder()
//                                        .id(subGroupType)
//                                        .title(subGroupName)
//                                        .build())
//                                .build()))
                        .goodsId(record.getId())
                        .id(record.getId())
                        .progressStatus(progressStatus)
                        .releaseDate(record.getOnsellTime())
                        .videoNum(record.getMediaSummary().getCount())
                        .build());

            }
            return new CommonDataView.HandleResult(page.isLast());
        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }

    }

    @Override
    public List query() {
        if (filter != null && filter != PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED)
            return new LinkedList();
        try {
            DeleteBuilder<LearnVideoModel, String> deleteBuilder = learnVideoModelDao.deleteBuilder();
            deleteBuilder.where()
                    .eq(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED)
                    .or()
                    .eq(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_PUBLISHED)
                    .or()
                    .eq(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_IN_REVIEW)
                    .or()
                    .eq(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING)
                    .or()
                    .eq(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_REJECT);

            deleteBuilder.delete();
            return learnVideoModelDao.queryBuilder()
                    .where()
                    .eq(LearnVideoModel.USER_ID_FIELD, AccountUtil.getCurrentUser().getId())
                    .and()
                    .ne(LearnVideoModel.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_DELETE)
                    .and()
                    .ne(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED)
                    .and()
                    .ne(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_PUBLISHED)
                    .and()
                    .ne(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_IN_REVIEW)
                    .and()
                    .ne(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_REJECT)
                    .and()
                    .ne(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING)
                    .query();
        } catch (Exception e) {
            return new LinkedList();
        }
    }

    @Override
    public int compare(Object o1, Object o2) {
        long diff = ((LearnVideoModel) o2).getReleaseDate() - ((LearnVideoModel) o1).getReleaseDate();
        if (diff > 0) {
            return 1;
        } else if (diff == 0) {
            return 0;
        } else {
            return -1;
        }
    }

    @Override
    public boolean equal(Object o1, Object o2) {
        LearnVideoModel model1 = (LearnVideoModel) o1;
        LearnVideoModel model2 = (LearnVideoModel) o2;
        return model1.getId().equals(model2.getId()) || model1.getGoodsId().equals(model2.getGoodsId());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void setFilter(Integer filter) {
        this.filter = filter;
        EventBus.getDefault().post(EventMMLearnVideoFilter.newBuilder().build());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventServerChangeMomentStatus event) {
        if (event.getSubject().equals(Moment.SUBJECT_VIDEO_COURSE)) {
            int progressStatus;
            switch (event.getTargetStatus()) {
                case Moment.STATUS_IN_REVIEW:
                    progressStatus = PublishUtil.PROGRESS_STATUS_IN_REVIEW;
                    break;
                case Moment.STATUS_REJECT:
                    progressStatus = PublishUtil.PROGRESS_STATUS_REJECT;
                    break;
                case Moment.STATUS_PUT_ON:
                    progressStatus = PublishUtil.PROGRESS_STATUS_PUBLISHED;
                    break;
                case Moment.STATUS_SAVE:
                    progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                    break;
                case Moment.STATUS_REVIEW_PASSED:
                    progressStatus = PublishUtil.PROGRESS_STATUS_PUBLISHED;
                    break;
                case Moment.STATUS_GET_OFF:
                    progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                    break;
                case Moment.STATUS_TRANSCODING:
                    progressStatus = PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING;
                    break;
                default:
                    progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                    break;
            }
            int upLimit = mmLearnVideoAdapter.getData().size();
            for (int i = 0; i < upLimit; ++i) {
                LearnVideoModel learnVideoModel = mmLearnVideoAdapter.getItem(i);
                if (event.getMomentId().equals(learnVideoModel.getGoodsId())) {
                    learnVideoModel.setProgressStatus(progressStatus);
                    learnVideoModel.setRejectReason(event.getMessage());
                    try {
                        LearnVideoModelDao.getDao().update(learnVideoModel);
                    } catch (SQLException e) {
                    }
                    mmLearnVideoAdapter.setData(i, learnVideoModel);
                    return;
                }
            }
        }
    }

}
